<?php

class InventoryController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }
    protected function clearValue($value){
        return str_ireplace(',','',$value);
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'users'=>array('@'),
            ),

            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }


    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Inventory;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Inventory']))
        {
            $model->attributes=$_POST['Inventory'];        
            if($model->save()){
                if($model->reworkable)
                {
                    $reworkableModelU = new Inventory;
                    $reworkableModelU->attributes = $_POST['Inventory'];     
                    $reworkableModelU->partno = $model->partno.'/U';
                    $reworkableModelU->kind = Inventory::PART_USED;
                    $reworkableModelU->save();

                    $reworkableModelR = new Inventory;
                    $reworkableModelR->attributes = $_POST['Inventory'];     
                    $reworkableModelR->partno = $model->partno.'/R';
                    $reworkableModelR->kind = Inventory::PART_REFURB;
                    $reworkableModelR->save();
                }
                $this->redirect(array('update','id'=>$model->partno));
            }

        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);        
        if(isset($_POST['Inventory']))
        {
            // echo '<pre>';
            // var_dump($_POST['Inventory']);
            // exit();

            $model->attributes=$_POST['Inventory'];

            $model->lastprice = $this->clearValue($model->lastprice);
            $model->averagecost =$this-> clearValue($model->averagecost);
            $model->baseprice = $this->clearValue($model->baseprice);
            $model->pricea = $this->clearValue($model->pricea);
            $model->priceb = $this->clearValue($model->priceb);
            $model->pricec = $this->clearValue($model->pricec);
            if($model->save())
            {
                if($model->reworkable&&strpos($model->partno,'/R') === false&&strpos($model->partno,'/U') === false)
                {
                    $existingModelCoupleUR = Inventory::getExistingPartForPrimaryPart($model->partno);                    
                    if( $existingModelCoupleUR['/R']&& $existingModelCoupleUR['/U'])
                    {
                        $reworkableModelU = $existingModelCoupleUR['/R'];
                        $reworkableModelU->description = $model->description;                        
                        $reworkableModelU->save();

                        $reworkableModelR = $existingModelCoupleUR['/U'];
                        $reworkableModelR->description = $model->description;  
                        $reworkableModelR->save();
                    }
                    else{
                        $reworkableModelU = new Inventory;
                        $reworkableModelU->attributes = $_POST['Inventory'];    
                        $reworkableModelU->kind = Inventory::PART_USED; 
                        $reworkableModelU->partno = $model->partno.'/R';
                        $reworkableModelU->save();

                        $reworkableModelR = new Inventory;
                        $reworkableModelR->attributes = $_POST['Inventory'];     
                        $reworkableModelR->kind = Inventory::PART_REFURB;
                        $reworkableModelR->partno = $model->partno.'/U';
                        $reworkableModelR->save();

                    }
                }        
            }

        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {

        // we only allow deletion via POST request
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(array('index'));

    }
    public function actionManufacturer($partno){
        $model=$this->loadModel($partno);
        if(isset($_POST['Inventory']))
        {
            $model->attributes=$_POST['Inventory'];
            $model->save();
        }
        $this->render('manufacturer',array(
            'model'=>$model,
        ));
    }
    public function actionNotes($partno){
        $model=$this->loadModel($partno);
        if(isset($_POST['Inventory']))
        {
            $model->attributes=$_POST['Inventory'];
            $model->save();
        }
        $this->render('notes',array(
            'model'=>$model,
        ));
    }
    /**
     * Lists all models.
     */
    public function actionIndex()
    {

        $this->render('index',array(

        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Inventory::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='inventory-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionList($pricecode=NULL,$query=NULL,$page=0,$sort=NULL,$dir=NULL,$status=NULL,$salesType=NULL){
        if($page>0) $page--;
        $order=CJSON::decode($sort);

        $crit=new CDbCriteria();
        if($query!=NULL){

            $crit->compare('partno', $query,true);
            $crit->compare('description', $query,true,'or');

            $crit->compare('cat', $query,true,'or');
            $crit->compare('mfg', $query,true,'or');
            $crit->compare('subcat', $query,true,'or');
            $crit->compare('model', $query,true,'or');

        }
        if($status!=NULL){
            $crit->compare('inactive', $status,'or');
        }
          if($salesType!=NULL){
            $crit->compare('salestype', $salesType,'or');
        }
        $crit->order=isset($order)?$order[0]['property'].' '.$order[0]['direction']:NULL;
        $data=new CActiveDataProvider('Inventory',array(
            'criteria'=>$crit,
            'pagination'=>array(
                'pageSize'=>20,
                'currentPage'=>$page
            )
        ));

        if($data!=NULL && count($data->getData())>0){
            $rs=array();
            $rs['totalCount']=$data->getTotalItemCount();
            foreach($data->getData() as $i=>$item){
                /* var Warehouse $item*/
                $rs['data'][$i]=$item->getAttributes();
                $rs['data'][$i]['inactive']=$item->getStatusText();
                $rs['data'][$i]['cost']=$item->getCost();
                if($pricecode){
                    $rs['data'][$i]['markupvalue']=$item->getMarkupValue($pricecode);
                }

                //$rs['data'][$i]['price']=$item->price;

            }
            echo json_encode($rs);
        }
        Yii::app()->end();

    }
    public function actionGetSubCategory($cat){
        $data= Inventory::model()->getSubCategoryList($cat);
        $text='';

        if(count($data)>0){
            foreach($data as $key=>$value){

                $text.="<option value='$key'>$value</option>";
            }
        }
        echo $text;
        Yii::app()->end();
    }
    public function actionGetPrice(){
        if(isset($_POST['Inventory'])){
            $inventory=new Inventory;
            $inventory->attributes=$_POST['Inventory'];
            $inventory->lastprice = $this->clearValue($inventory->lastprice);
            $inventory->averagecost =$this-> clearValue($inventory->averagecost);
            $inventory->baseprice = $this->clearValue($inventory->baseprice);
            $inventory->pricea = $this->clearValue($inventory->pricea);
            $inventory->priceb = $this->clearValue($inventory->priceb);
            $inventory->pricec = $this->clearValue($inventory->pricec);
            $result=Inventory::model()->calculatePrice(
                $inventory
            );
            echo json_encode($this->clearValue($result));
            Yii::app()->end();
        }
    }
    public function actionAdjust()
    {
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        $this->render('adjust');
    }
    public function actionmakeAdjust(){
        $result = $this->makeAdjust($_POST['data']);
        $this->sendAdjustResultEmail($result);
        echo $result;
    }

    protected function makeAdjust($data){
        $result = '';
        $result.= '<table border="1" cellpadding="2" cellspacing="2"  >
                <tr >
                 <th> &nbsp; Warehouse &nbsp;</th>
                <th> &nbsp; Partno &nbsp;</th>
                <th> &nbsp; Description &nbsp;</th>
                <th> &nbsp; Start QTY &nbsp;</th>
                <th> &nbsp; Count QTY &nbsp; </th>
                <th> &nbsp; Adjustment &nbsp;</th>
                
                </tr>
                ';
        foreach($data as $item){
            $addData = $item;
            $model = new Inventoryact();
            $data = new Inventoryact();
            $data->attributes = $item;
            $item = $data;
            $beforeQty = $model->getQty($item);

            $result.= '<tr>';
            $result.= '<td> &nbsp; '. Warehouse::getDescription($item->warehouse).'&nbsp;</td>';
            $result.= '<td> &nbsp; '.$item->partno.'&nbsp;</td>';
            $result.= '<td> &nbsp; '.$item->description.'&nbsp;</td>';
            $result.= '<td align="right">  '.(int)$beforeQty.'&nbsp;</td>';
            $result.= '<td align="right">  '. (int)$model->adjust($item,$addData).'&nbsp;</td>';
            $result.= '<td align="right">  '.-(int)($beforeQty - $model->getQty($item)).'&nbsp;</td>';
            $result.= '</tr>';




        }
        $result.='</table>';
        return $result;
    }

    protected function sendAdjustResultEmail($result){
        Yii::import('application.extensions.phpmailer.JPhpMailer');
        $mail = new JPhpMailer;

        $body = $result;
        $body.='Logged In User:'.getUserRealname(Yii::app()->user->name);


        $mail->SetFrom('no-reply@customerconnect.qsibanking.com', 'QSI, INC: Customer Connect');

        $mail->AddReplyTo("no-reply@customerconnect.qsibanking.com", "QSI, INC: Customer Connect");

        $mail->AddAddress('michael.bonza@qsibanking.com');
        //$mail->AddAddress('markitanm@gmail.com');
        $mail->Subject ='Adjust Inventory ALERT';

        $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

        $mail->MsgHTML($body);

        $mail->Send();
    }
    public function actionTransfer()
    {
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        $this->render('transfer');
    }
    public function actionmakeTransfer(){
        $result = '';
        $result.= '<table border="1" cellpadding="2" cellspacing="2"  >
                <tr >
                 <th> &nbsp; From &nbsp;</th>
                <th> &nbsp; To &nbsp;</th>
                <th> &nbsp; Part No &nbsp;</th>
                <th> &nbsp; Description &nbsp; </th>
                <th> &nbsp; Qty &nbsp;</th>
                <th> &nbsp; Error &nbsp;</th>
                </tr>
                ';
        foreach($_POST['data'] as $item){
            $addData = $item;
            $model = new Inventoryact();
            $data = new Inventoryact();
            $data->attributes = $item;
            $item = $data;
            $beforeQty = $model->getQty($item);
                if($beforeQty>=$item->qty){
            $result.= '<tr>';
            $result.= '<td> &nbsp; '. Warehouse::getDescription($item->warehouse).'&nbsp;</td>';
            $result.= '<td> &nbsp; '. Warehouse::getDescription($addData['towarehouse']).'&nbsp;</td>';
            $result.= '<td> &nbsp; '.$item->partno.'&nbsp;</td>';
            $result.= '<td> &nbsp; '.$item->description.'&nbsp;</td>';
            $result.= '<td> &nbsp; '.$item->qty.'&nbsp;</td>';
            $result.= '<td> &nbsp; NONE &nbsp;</td>';
            $result.= '</tr>';
            $model->transfer($item,$addData);
                } else {                
                    $result.= '<tr>';
                    $result.= '<td> &nbsp; '. Warehouse::getDescription($item->warehouse).'&nbsp;</td>';
                    $result.= '<td> &nbsp; '. Warehouse::getDescription($addData['towarehouse']).'&nbsp;</td>';
                    $result.= '<td> &nbsp; '.$item->partno.'&nbsp;</td>';
                    $result.= '<td> &nbsp; '.$item->description.'&nbsp;</td>';
                    $result.= '<td> &nbsp; '.$item->qty.'&nbsp;</td>';
                    $result.= '<td> &nbsp; <b style="color:red;">Error in qty</b>&nbsp;</td>';
                    $result.= '</tr>';
                }
        }
        $result.='</table>';
        $this->sendAdjustResultEmail($result);
        echo $result;
    }

    protected function sendTransferResultEmail($result){
        Yii::import('application.extensions.phpmailer.JPhpMailer');
        $mail = new JPhpMailer;

        $body = $result;

        $body.='Logged In User:'.getUserRealname(Yii::app()->user->name);

        $mail->SetFrom('no-reply@customerconnect.qsibanking.com', 'QSI, INC: Customer Connect');

        $mail->AddReplyTo("no-reply@customerconnect.qsibanking.com", "QSI, INC: Customer Connect");

        $mail->AddAddress('michael.bonza@qsibanking.com');
        //$mail->AddAddress('markitanm@gmail.com');
        $mail->Subject ='Transfer Inventory ALERT';

        $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

        $mail->MsgHTML($body);

        return $mail->Send();
    }
    public function actionImportAdjustData(){
        $file = CUploadedFile::getInstanceByName('file');
        if($file!=null && isset($_POST['warehouse']) && isset($_POST['reason'])){
            if($file->getExtensionName() == 'csv'){
                $tempName = 'documents/temp/'.time().'.'.$file->extensionName;
                if($file->saveAs($tempName,true)){
                      $f = file_get_contents($tempName);
                    if ($f !== false) {
                        $file_data = explode("\r", $f);
                        $data = array();

                        for ($i = 0; $i < count($file_data); $i++) {

                            if (trim($file_data[$i])) {
                                $lineArray = explode(',', $file_data[$i]);

                                $data[] = array(
                                    'partno' => $lineArray[0],
                                    'qty' => $lineArray[1],
                                    'warehouse' => $_POST['warehouse'],
                                    'reason' => $_POST['reason']
                                );
                            }
                        }
                        $result = $this->makeAdjust($data);
                        $this->sendAdjustResultEmail($result);
                        $this->showAjaxMessage('Import successful',true);
                    }
                    unlink($tempName);
                }
                $this->showAjaxMessage('Can not open uploaded file',false);
            }else{
                $this->showAjaxMessage('Only csv file is accepted',false);
            }
        }else{
            $this->showAjaxMessage('Invalid parameter',false);
        }

    }

}
 
